package com.zhang.service.impl;

import com.zhang.entity.ProductImage;
import com.zhang.entity.ProductSalePropertyKey;
import com.zhang.entity.ProductSalePropertyValue;
import com.zhang.entity.ProductSpu;
import com.zhang.mapper.ProductSpuMapper;
import com.zhang.service.ProductImageService;
import com.zhang.service.ProductSalePropertyKeyService;
import com.zhang.service.ProductSalePropertyValueService;
import com.zhang.service.ProductSpuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author zbw
 * @since 2022-04-07
 */
@Service
public class ProductSpuServiceImpl extends ServiceImpl<ProductSpuMapper, ProductSpu> implements ProductSpuService {
    @Autowired
    private ProductImageService imageService;
    @Autowired
    private ProductSalePropertyKeyService salePropertyKeyService;
    @Autowired
    private ProductSalePropertyValueService salePropertyValueService;

    //添加SPU信息
    @Override
    @Transactional
    public void saveProductSpu(ProductSpu productSpu) {
        //1.保存基本的spu信息
        baseMapper.insert(productSpu);
        Long spuId = productSpu.getId();//获取商品id
        //2.保存spu的图片信息
        List<ProductImage> productImageList = productSpu.getProductImageList();
        if (!CollectionUtils.isEmpty(productImageList)){
            for (ProductImage productImage : productImageList) {
                productImage.setProductId(spuId);
            }
            imageService.saveBatch(productImageList);
        }
        //3.保存spu的销售属性key的信息
        List<ProductSalePropertyKey> salePropertyKeyList = productSpu.getSalePropertyKeyList();
        if (!CollectionUtils.isEmpty(salePropertyKeyList)){
            for (ProductSalePropertyKey productSalePropertyKey : salePropertyKeyList) {
                productSalePropertyKey.setProductId(spuId);
                //4.保存spu的销售属性value的信息
                List<ProductSalePropertyValue> salePropertyValueList = productSalePropertyKey.getSalePropertyValueList();
                for (ProductSalePropertyValue productSalePropertyValue : salePropertyValueList) {
                    productSalePropertyValue.setProductId(spuId);
                    productSalePropertyValue.setSalePropertyKeyName(productSalePropertyKey.getSalePropertyKeyName());
                }
                salePropertyValueService.saveBatch(salePropertyValueList);
            }
            salePropertyKeyService.saveBatch(salePropertyKeyList);
        }
    }
}
